<template>

  <div>
     <div> 
        <section v-loading="loading"></section>
    </div>
    <head-top></head-top>
    <el-row style="margin-top: 20px">
      <el-col :span="12" :offset="4">
        <el-form
          :model="formData"
          :rules="rules"
          ref="formData"
          label-width="110px"
          class="demo-formData"
        >

          <el-form-item label="景点名称" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <div id="map-container" style="width: 500px; height: 400px"></div>
          <el-form-item label="详细地址" prop="address">
            <el-autocomplete
              style="width: 100%"
              popper-class="autoAddressClass"
              v-model="addr.addr"
              :fetch-suggestions="querySearchAsync"
              :trigger-on-focus="false"
              placeholder="详细地址"
              @select="handleSelect"
              
            >
     
            </el-autocomplete>
          </el-form-item>

          <el-form-item label="景点介绍" prop="introduction">
            <el-input v-model="formData.introduction"></el-input>
          </el-form-item>
          <el-form-item label="景点公告" prop="annocement">
            <el-input v-model="formData.annocement"></el-input>
          </el-form-item>
          <el-form-item label="票名称" prop="ticketDes">
            <el-input v-model="formData.ticketDes"></el-input>
          </el-form-item>
          <el-form-item label="票的价格" prop="ticketPrice">
            <el-input v-model="formData.ticketPrice"></el-input>
          </el-form-item>

          <el-form-item label="景点图片" label-width="100px">
            <span>最多上传五张</span>
            <el-upload
              action=""
              class="avatar-uploader"
              multiple
              accept="image/*"
              limit="5"
              :file-list="fileList"
              :on-change="fileChange"
              :on-remove="fileRemove"
              :auto-upload="false"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item class="button_submit">
            <el-button type="primary" @click="submitForm('formData')"
              >立即创建</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>
   
<script>
import headTop from "@/components/headTop";

import loadBMap from "@/api/baiduMap";
import { addScenery, importFile } from "@/api/scenery";
import { getQueryResults } from "@/api/baiduMap";

export default {
  data() {
    return {
      city: {},
      map: "", //地图实例
      mk: "", //Marker实例
      sceneryPic: {},
      addr:{},
      formData: {
        name: "", //景点名称
        address: "", //地址
        addr: {},
        introduction: "",
        annocement: "",
        ticketDes: "", //介绍
        ticketPrice: "",
      },
      addrPoint :'',
      loading:false,

      
      rules: {
        name: [{ required: true, message: "请输入店铺名称", trigger: "blur" }],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
        ticketDes: [
          { required: true, message: "请输入票的名称", trigger: "blur" },
        ],
        ticketPrice: [
          { required: true, message: "请输入票的价格", trigger: "blur" },
        ],
      },
      sceneryPic: {},
      selectedSceneryId: -1,
      fileList: [],
    };
  },
  components: {
    headTop,
  },
  async mounted() {
    await loadBMap("F0QZjfxl5SM6vG3XwdoM5UVVjGWwPM0K"); //加载引入BMap
    this.initmyMap();
  },

  methods: {
    async initData() {},

    querySearchAsync(str,cb){
      var options = {
        onSearchComplete: function(res){ //检索完成后的回调函数
          var s = [];
          console.log("local",local);
          if (local.getStatus() == BMAP_STATUS_SUCCESS){
            console.log('isok',res);
            for (var i = 0; i < res.getCurrentNumPois(); i ++){
              console.log('res.getpoi',res.getPoi(i));
              let r = res.getPoi(i);
              //这里必须设置value
              r.value = r.province+r.address+r.title
              s.push(r);
            }
            console.log("querySearchAsync s",s);
            cb(s) //获取到数据时，通过回调函数cb返回到<el-autocomplete>组件中进行显示
          } else{
            console.log("querySearchAsync else");
            cb(s)
          }
        }
      }
      var local = new BMap.LocalSearch(this.map, options) //创建LocalSearch构造函数
      local.search(str) //调用search方法，根据检索词str发起检索
    },
    handleSelect(item) {
      //选中必须记录信息
     console.log("item select",item);
      const latitude = item.point.lat
      const longitude = item.point.lng  
      const {province,city,title,address}=item
         let addr= province+address+title
         //选中跟新景点信息
        this.addr = {province,city,latitude,longitude,addr}
      this.map.clearOverlays() //清除地图上所有覆盖物
      this.mk = new BMap.Marker(item.point) //根据所选坐标重新创建Marker
      this.map.addOverlay(this.mk) //将覆盖物重新添加到地图中
      this.map.panTo(item.point) //将地图的中心点更改为选定坐标点
      let that = this;
     this.mk.addEventListener('dragend', function(e){
        that.getAddrByPoint(e.point) //拖拽结束后调用逆地址解析函数，e.point为拖拽后的地理坐标
    })
    },


  initmyMap(lat=28.689454978197837,lng=115.86458548977238) { 
      console.log("initMap lat",lat,"lng",lng);
      var point = new BMap.Point(Number(lng).toFixed(5),Number(lat).toFixed(5));
//新建地图实例，enableMapClick:false ：禁用地图默认点击弹框
      this.map = new BMap.Map("map-container", { enableMapClick: false }); 
      this.map.centerAndZoom(point, 19);
      this.map.enableScrollWheelZoom(true); //启用滚轮放大缩小，默认禁用
       this.mk = new BMap.Marker(point,{enableDragging:true})
      this.map.addOverlay(this.mk)
      let that = this;
     this.mk.addEventListener('dragend', function(e){
    
        that.getAddrByPoint(e.point) //拖拽结束后调用逆地址解析函数，e.point为拖拽后的地理坐标
    })

    
    },

    //添加地图控件
    addMapContro(){
        var navigationControl = new BMap.NavigationControl({
        //创建一个特定样式的地图平移缩放控件
        anchor: BMAP_ANCHOR_TOP_RIGHT, //靠右上角位置
        type: BMAP_NAVIGATION_CONTROL_SMALL, //SMALL控件类型
      });
      this.map.addControl(navigationControl); //将控件添加到地图
      var geolocationControl = new BMap.GeolocationControl({
        anchor: BMAP_ANCHOR_BOTTOM_LEFT,
      }); //创建一个地图定位控件
      geolocationControl.addEventListener("locationSuccess", function (e) {
        //绑定定位成功后事件
        that.getAddrByPoint(e.point); //定位成功后调用逆地址解析函数
      });
      geolocationControl.addEventListener("locationError", function (e) {
        //绑定定位失败后事件
        alert(e.message);
      });
      this.map.addControl(geolocationControl); //将控件添加到地图
    },
    /**
 * 逆地址解析函数（根据坐标点获取详细地址）
 * @param {Object} point   百度地图坐标点，必传
 */
  getAddrByPoint(point){
  var that = this;
  var geco = new BMap.Geocoder();
  geco.getLocation(point, function(res){
  	console.log(res)  //内容见下图
    that.mk.setPosition(point) //重新设置标注的地理坐标
    that.map.panTo(point)  //将地图的中心点更改为给定的点
    console.log("getAddrBypoint res",res);
     const latitude = res.point.lat
      const longitude = res.point.lng
      const {province,city} = res.addressComponents
      //跟新当前位置
      that.addr = {latitude,longitude,province,city,addr:res.address}
  })
},
    


    //检测文件变动获取文件
    fileChange(file, fileList) {
      this.fileList = fileList;
    },
    //检测文件删除
    fileRemove(file, fileList) {
      this.fileList = fileList;
    },
    //手动上传图片
    submitUpload(id) {
      console.log("this.fileList", this.fileList);
      let formData = new FormData(); //  将文件封装进FormData
      this.fileList.forEach((file) => {
        formData.append("file", file.raw);
      });
      console.log("fromdata", formData);
      // formData.append(",属性名",“你想附带的数据”) //附带数据
      // 调用上传接口
      importFile(id, formData).then(
        (res) => {
          //手动上传无法触发成功或失败的钩子函数，因此需要手动调用
          if (res.code >= 0) {
            this.$message.success(res.message);
            location.reload();
          } else {
            this.$message.error(res.message);
          }
        },
        (err) => {
          this.upError(err);
        }
      );
    },

    async  submitForm(formName) {
      let that = this;
      this.formData.address= this.addr.addr
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading=true
          this.formData.addr = this.addr
         console.log(this.formData);
          addScenery(that.formData).then(async(res) => {
            console.log("addScenery ", res);
            if (res.code >= 0) {
             await that.submitUpload(res.data.id);
              this.loading=false
              that.$message.success("上传成功");
            } else {
              that.$message.error("上传失败");
            }
          });
        }
         this.loading=false
      });
    },
  },
};
</script>

<style lang="less">
@import "../style/mixin";
.button_submit {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.el-table .info-row {
  background: #c9e5f5;
}

.el-table .positive-row {
  background: #e2f0e4;
}
.autoAddressClass li{

    i.el-icon-search {margin-top:11px;}
    .mgr10 {margin-right: 10px;}
    .title {
      text-overflow: ellipsis;
      overflow: hidden;
    }
}
.autoAddressClass  .address {
      line-height: 1;
      font-size: 12px;
      color: #b4b4b4;
      margin-bottom: 5px;
}
  




</style>
